package org.dandelion.account;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import org.dandelion.R;
import org.dandelion.account.util.Account;
import org.dandelion.account.util.DBHelper;


public class AccInfoActivity extends AppCompatActivity {
    TextView typetv;
    RadioGroup RG, RG2;
    EditText et1, et2;
    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_acc_info);

        typetv = findViewById(R.id.typetv);
        RG = findViewById(R.id.RadioGroup1);
        RG2 = findViewById(R.id.RadioGroup2);
        button = findViewById(R.id.button);
        et1 = findViewById(R.id.money);
        et2 = findViewById(R.id.info);
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        String type = bundle.getString("type");
        String date = bundle.getString("dates");
        typetv.setText((date + "记录  " + type));

        if (!type.equals("支出")) {
            RG.setVisibility(View.INVISIBLE);
            RG2.setVisibility(View.VISIBLE);
        }

        button.setOnClickListener(v -> {
            if (et1.getText().toString().isEmpty()) {
                Toast.makeText(AccInfoActivity.this, "金额未填写！",
                        Toast.LENGTH_SHORT).show();
            } else if (getRG(RG).isEmpty() && getRG(RG2).isEmpty()) {
                Toast.makeText(AccInfoActivity.this, "类型未选择！",
                        Toast.LENGTH_SHORT).show();
            } else {
                double money = Double.parseDouble(et1.getText().toString());
                String rb = getRG(RG) + getRG(RG2);
                String info = et2.getText().toString();
                Account account = new Account(type, money, rb, info, date);
                DBHelper helper = new DBHelper(AccInfoActivity.this);
                helper.insert(account);
                finish();
            }
        });
    }

    public String getRG(RadioGroup RG) {
        String result = "";

        for (int n = 0; n < RG.getChildCount(); n++) {
            RadioButton r = (RadioButton) RG.getChildAt(n);
            if (r.isChecked()) {
                result = r.getText().toString();
            }
        }
        return result;
    }
}